package com.zzz.code_replace;

import java.io.File;
import java.util.List;
import java.util.Map;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

public class CodeReplace {
	private static final List<String> ext = StrUtil.splitTrim(".java,.xml,.js,.json,.txt", ",");

	public static void codeReplace(String folder, Map<String, String> map) {
		String path = StrUtil.replace(folder, "\\", "/");
		path = StrUtil.removeSuffix(path, "/");
		String left = StrUtil.subBefore(path, "/", true);
		String right = StrUtil.subAfter(path, "/", true);
		String subPath = right + "_";
		String newPath = left + "/" + subPath;
		codeReplace(path, newPath, map);
	}

	private static void codeReplace(String oldPath, String newPath, Map<String, String> map) {
		System.out.println("oldPath=" + oldPath);
		System.out.println("newPath=" + newPath);
		File oldFile = new File(oldPath);
		codeReplace(oldPath, newPath, oldFile, map);
	}

	private static void codeReplace(String oldPath, String newPath, File oldFile, Map<String, String> map) {
		if (oldFile.isDirectory()) {
			File[] listFiles = oldFile.listFiles();
			for (File subFile : listFiles) {
				codeReplace(oldPath, newPath, subFile, map);
			}
		} else {
			String absolutePath = oldFile.getAbsolutePath();
			absolutePath = absolutePath.replace("\\", "/");
			String subPath = StrUtil.removePrefix(absolutePath, oldPath);
			subPath = StrUtil.removePrefix(subPath, "/");
			subPath = TextParser.repaceText(subPath, map);
			String newPathAll = newPath + "/" + subPath;
			copyFile(absolutePath, newPathAll, map);
		}

	}

	private static void copyFile(String oldPath, String newPath, Map<String, String> map) {
		String curExt = StrUtil.subAfter(oldPath, "/", true);
		curExt = StrUtil.subAfter(curExt, ".", true);
		if (ext.contains("." + curExt)) {
			TextParser.copy(oldPath, newPath, map);
		} else {
			FileUtil.copy(oldPath, newPath, true);
		}
	}

}
